package com.wxtf.platform.plugins.group;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
/**
 * <li>Title: UserService.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.user</li>
 * <li>Description: 用户管理-表T_USER</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 5, 2012 10:08:48 AM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class GroupAction extends LogicBase implements CommonsCallProvider {
	private static Log log = LogFactory.getLog(GroupAction.class);

	public GroupAction(String jsonArray) {
		
	}


	public Object onInit(Object jsonArray) {
		return null;
	}


	public Object onCreate(Object jsonArray) {
		return null;
	}


	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getExtendData());
				return msg.toString();
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("listUser".equals(this.getMethodName())) {
				msg = this.listUser(this.getExtendData());
				return msg.toString();
			} else if ("saveUser".equals(this.getMethodName())) {
				msg = this.saveUser(this.getLogicData());
			} else if ("delUser".equals(this.getMethodName())) {
				msg = this.delUser(this.getLogicData());
			} else if ("listRole".equals(this.getMethodName())) {
				msg = this.listRole(this.getLogicData());
				return msg.toString();
			} else if ("saveRole".equals(this.getMethodName())) {
				msg = this.saveRole(this.getLogicData());
			} else if ("delRole".equals(this.getMethodName())) {
				msg = this.delRole(this.getLogicData());
			} else if ("listGroup4User".equals(this.getMethodName())) {
				msg = this.listGroup4User(this.getLogicData());
				return msg.toString();
			} else if ("listGroup4Role".equals(this.getMethodName())) {
				msg = this.listGroup4Role(this.getLogicData());
				return msg.toString();
			} else if ("listRole4Group".equals(this.getMethodName())) {//用户组下的角色
				msg = this.listRole4Group(this.getExtendData());
				return msg.toString();
			} else if ("listUser4Group".equals(this.getMethodName())) {//用户组下的用户
				msg = this.listUser4Group(this.getExtendData());
				return msg.toString();
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
			//log.info(this.getClass().getName() +":"+this.getMethodName() + " -> " + msg);
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	private String[] fields = { "group_id", "gparent_id", "caption", "logic_code", "action" };
	@Override
	public Object select(Object jsonArray) throws Exception {
		JSONArray array = null;
		List<Map<String,Object>> list =  AccessDataBaseUtil.query4ListMap(fields1, sql, new Object[] { "0" });
		list = this.getGroupByPid(list);
		String msg="";
		String rootNode = "\"id\":\"0\", \"gparent_id\":\"0\", \"text\":\"用户组根节点\", \"logic_code\":\"\", \"action\":\"\"";
		if(null == list || list.size() <= 0){
			msg = "{\"Rows\":[{" + rootNode + ", \"children\":[]}]}";
		} else {
			array = JSONArray.fromObject(list);
			msg = "{\"Rows\":[{" + rootNode + ", \"children\":" + array.toString() + "}]}";
		}    
		return msg;
	}

	private String[] fields1 = { "id", "gparent_id", "text", "logic_code", "action"};
	private String sql = "select group_id,gparent_id,caption,logic_code,action from t_group where gparent_id = ? order by logic_code";
	private List<Map<String,Object>> getGroupByPid(List<Map<String,Object>> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		for(Map<String,Object> map: list){
			String id = String.valueOf(map.get("id"));
			List<Map<String,Object>> list1 = AccessDataBaseUtil.query4ListMap(fields1, sql, new Object[] { id });
			map.put("children", list1);
			this.getGroupByPid(list1);
		}
		return list;
	}
	
	/** 
	 * 描述：listGroup4User 用户选组时-组树
	 * @param jsonArray
	 * @return
	 * @CreateOn Jul 23, 2012  9:47:18 AM
	 * @author chun_chang
	 * @throws Exception 
	 */
	public Object listGroup4User(Object jsonArray) throws Exception{
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("user_id");
		String name = jsonObject.getString("name");//组名称
		
		//将已经选中的组id放入集合中
		String sql = "select group_id from t_user_group where user_id = ?";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { id });
		Set<String> set = new HashSet<String>();
		for (Object o : list1) {
			set.add(String.valueOf(o));
		}
		
		String sql1 = "select group_id, caption,'' from t_group where gparent_id = ?";
		if (StringUtils.isNotBlank(name)) {
			sql1 += " and caption like '%" + name + "%'";
		}
		
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields2, sql1, new Object[] { "0" });
		list = this.getGroupByPid1(list, sql1, set, "0");
		
		if(list!=null){
			array = JSONArray.fromObject(list);
			return array.toString();
		}else{
			return "[]";
		}
		
		
	}

	private String[] fields2 = { "id", "text", "oth_id" };
	private List<Map<String, Object>> getGroupByPid1(List<Map<String, Object>> list, String sql, Set<String> set, String id1) throws Exception {
		if (null == list || list.size() <= 0) {
			return null;
		}
		for (Map<String, Object> map : list) {
			String id = String.valueOf(map.get("id"));
			List<Map<String, Object>> list1 = AccessDataBaseUtil.query4ListMap(fields2, sql, new Object[] { id });
			boolean bool = set.add(id);
			if (bool) {
				set.remove(id);
			} else {
				map.put("oth_id", id);
			}
			map.put("ischecked", !bool);
			map.put("children", list1);
			this.getGroupByPid1(list1, sql, set, id);
		}
		return list;
	}
	
	/** 
	 * 描述：listGroup4Role 角色选组-组树
	 * @param jsonArray
	 * @return
	 * @CreateOn Jul 23, 2012  10:16:45 AM
	 * @author chun_chang
	 * @throws Exception 
	 */
	public Object listGroup4Role(Object jsonArray) throws Exception{
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("roleId");
		String name = jsonObject.getString("groupName");//组名称
		
		//将已经选中的组id放入集合中
		String sql = "select group_id from t_group_role where role_id = ?";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { id });
		Set<String> set = new HashSet<String>();
		for (Object o : list1) {
			set.add(String.valueOf(o));
		}
		
		String sql1 = "select group_id, caption,'' from t_group where gparent_id = ?";
		if (StringUtils.isNotBlank(name)) {
			sql1 += " and caption like '%" + name + "%'";
		}
		
		List<Map<String, Object>> list = AccessDataBaseUtil.query4ListMap(fields2, sql1, new Object[] { "0" });
		list = this.getGroupByPid1(list, sql1, set,id);
		
		if(list!=null){
			array = JSONArray.fromObject(list);
			return array.toString();
		}else{
			return "[]";
		}
	}
	
	@Override
	public Object insert(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		obj[0] = AccessDataBaseUtil.getPKUUID();

		String quertsql = "select count(*) from t_group where caption = ?";
		int cnt = AccessDataBaseUtil.queryForInt(quertsql, new Object[] { jsonObject.getString("caption") });
		if(cnt > 0) {
			return "\"该节点已存在\"";
		} else {
			sql = "insert into t_group(group_id,gparent_id,caption,logic_code,action) values(?,?,?,?,?)";
			AccessDataBaseUtil.executeSQLUpdate(sql, obj);
			return "\"添加成功\"";
		}
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 0; j < fields.length - 1; j++) {
			obj[j] = jsonObject.getString(fields[j + 1]);
		}
		obj[obj.length - 1] = jsonObject.getString(fields[0]);
		sql = "update t_group set gparent_id = ?,caption = ?,logic_code = ?,action = ? where group_id = ?";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		return "\"编辑成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from t_group where group_id = ?";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	public Object listUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String userName = jsonObject.getString("userName");
		String jigou = jsonObject.getString("jigou");
		//sql = " from t_user r left join t_user_group s on r.user_id = s.user_id and s.group_id = ? WHERE  r.USER_ID NOT IN(SELECT user_id FROM t_user_group WHERE group_id="+groupId+")";
		sql = " from t_user a left join t_user_group b on a.user_id = b.user_id" +
				" left join t_user_department c on a.user_id=c.user_id" +
				" left join t_department d on c.department_id=d.department_id" +
				" WHERE a.USER_ID NOT IN(SELECT user_id FROM t_user_group WHERE group_id='"+groupId+"')";
		if (StringUtils.isNotBlank(userName)) {
			sql += "  and a.caption like '%" + userName + "%'";
		}
		if (StringUtils.isNotBlank(jigou)) {
			sql += "  and d.caption like '%" + jigou + "%'";
		}
		String countSql = "select count(*) " + sql;
		String querySql = "select a.user_id,a.caption c1,b.group_id,d.caption c2 " + sql + " order by b.group_id desc";
		String[] fields = { "user_id", "caption", "group_id", "jigou" };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	public Object saveUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		sql = "delete from T_USER_GROUP where GROUP_ID = '" + groupId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, userId);
		
		buff.setLength(0);
		for (String id1 : userId) {
			buff.append("insert into T_USER_GROUP(U_G_ID,GROUP_ID,USER_ID)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(groupId).append("',")
				.append("'").append(id1).append("'")
				.append(")");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"添加成功\"";
	}
	
	public Object delUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		sql = "delete from T_USER_GROUP where GROUP_ID = '" + groupId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, userId);
		return "\"移除成功\"";
	}
	public Object listRole(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String name = jsonObject.getString("roleName");
		String countSql = "";
		String querySql = "";
		String[] fields = { "role_id", "caption", "group_id" };
		/*
		 * 1.看当前节点是否有上级节点
		 * 2.没有：列所有的角色
		 * 3.有：找当前组G1的上级G2是否有角色
		 * a.有，列出角色
		 * b.没有，当前组G2不是一级节点，返回空
		 */
		//列出当前组的上级组信息
		sql = "select c.group_id from t_group c where c.group_id = (select gparent_id from t_group where group_id = ?)";
		List<Object> list1 = AccessDataBaseUtil.query4List(sql, new Object[] { groupId });

		String group_id1 = "";
		boolean bool = false;
		if(null != list1 && list1.size() > 0){
			group_id1 = String.valueOf(list1.get(0));
			bool = true;
		}
		if(bool){//取到了父级节点
			//看父级节点是否有角色
			sql = "select r.role_id, r.caption, s.group_id from t_role r, t_group_role s where r.role_id = s.role_id and s.group_id = ?";
			List<Map<String, Object>> list2 = AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { group_id1 });
			if(null == list2 || list2.size() <= 0){
				return "{\"Total\":\"0\",\"Rows\":[]}";
			} else {
				sql = " from" +
						" (select r.role_id, r.caption,'' from t_role r, t_group_role s where r.role_id = s.role_id and s.group_id = ?) aa" +
						" left join" +
						" (select rr.role_id, rr.caption, ss.group_id from t_role rr, t_group_role ss where rr.role_id = ss.role_id and ss.group_id = ?) bb" +
						" on aa.role_id = bb.role_id WHERE aa.role_id NOT IN(SELECT role_id FROM t_group_role WHERE group_id='" + groupId + "')";
				if (StringUtils.isNotBlank(name)) {
					sql += " and aa.caption like '%" + name + "%'";
				}
				
				countSql = "select count(*) " + sql;
				querySql = "select aa.role_id, aa.caption, bb.group_id  " + sql + " order by bb.group_id";
				Object[] params = { group_id1, groupId };
				return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
			}
		} else {//当前组G1是一级节点
			//select r.role_id,r.caption,t.group_id from t_role r left join t_group_role t on r.role_id = t.role_id and t.group_id = ?
			sql = " from t_role r left join t_group_role t on r.role_id = t.role_id and t.group_id = ? WHERE 1=1 AND r.role_id NOT IN(SELECT role_id FROM t_group_role WHERE group_id='" + groupId + "')";
			if (StringUtils.isNotBlank(name)) {
				sql += " and r.caption like '%" + name + "%'";
			}
			countSql = "select count(*)" + sql;
			querySql = "select r.role_id,r.caption,t.group_id" + sql + " order by r.LOGIC_CODE asc";
			return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ groupId });
		}
	}
	public Object saveRole(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String ids = jsonObject.getString("roleId");
		String[] id = ids.split(",");
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		for (String id1 : id) {
			buff.append("'").append(id1).append("',");
		}
		buff.append("''");
		sql = "delete from T_GROUP_ROLE where GROUP_ID = '" + groupId + "' and ROLE_ID in (" + buff.toString() + ")";
		list.add(sql);
		
		buff.setLength(0);
		for (String id1 : id) {
			buff.append("insert into T_GROUP_ROLE(G_R_ID,GROUP_ID,ROLE_ID)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(groupId).append("',")
				.append("'").append(id1).append("')");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"添加成功\"";
	}
	
	public Object delRole(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String groupId = jsonObject.getString("groupId");
		String ids = jsonObject.getString("roleId");
		String[] id = ids.split(",");

		StringBuffer buff = new StringBuffer();
		for (String id1 : id) {
			buff.append("'").append(id1).append("',");
		}
		buff.append("''");

		sql = "delete from T_GROUP_ROLE where GROUP_ID = ? and ROLE_ID in (" + buff.toString() + ")";
		AccessDataBaseUtil.executeSQLUpdate(sql, new Object[] { groupId });
		return "\"移除成功\"";
	}
	
	public Object listUser4Group(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("id");
		String userName = jsonObject.getString("userName");
		String jigou = jsonObject.getString("jigou");
		sql = " from t_user a inner join t_user_group b on a.user_id = b.user_id and b.group_id='"+id+"'";
		if (StringUtils.isNotBlank(userName)) {
			sql += "  and a.caption like '%" + userName + "%'";
		}
		sql += " left join t_user_department c on a.user_id=c.user_id" +
			" left join t_department d on c.department_id=d.department_id";
		if (StringUtils.isNotBlank(jigou)) {
			sql += "  where d.caption like '%" + jigou + "%'";
		}
		String countSql = "select count(1)" + sql;
		String querySql = "select a.user_id,a.caption c1,d.caption c2" + sql;
		String[] fields = { "user_id", "caption", "jigou" };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}
	
	public Object listRole4Group(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("id");
		String roleName = jsonObject.getString("roleName");
		sql = " from t_role r,t_group_role s where r.role_id = s.role_id and s.group_id = ?";
		if (StringUtils.isNotBlank(roleName)) {
			sql += "  and r.caption like '%" + roleName + "%'";
		}
		String countSql = "select count(1)" + sql;
		String querySql = "select r.role_id, r.caption" + sql + " order by r.LOGIC_CODE";
		String[] fields = { "role_id", "caption" };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ id });
	}
	
	
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		return null;
	}

}
